package com.fowo.api.syncAmazon.api;

import cn.hutool.core.date.DateUtil;
import com.amazon.spapi.api.ReportsApi;
import com.amazon.spapi.model.reports.CreateReportSpecification;
import com.amazon.spapi.model.reports.Report;
import com.amazon.spapi.model.reports.ReportDocument;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.TmpReimbursements;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.TmpReimbursementsServiceImpl;
import com.fowo.api.syncAmazon.util.AmazonUtil;
import com.fowo.api.syncAmazon.util.AmzDateUtils;
import com.fowo.api.syncAmazon.util.GeneralUtil;
import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Slf4j
@Component
public class ReimbursementsReportService extends ReportService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private AmazonUtil amazonUtil;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpReimbursementsServiceImpl tmpReimbursementsService;

    /**
     * 赔偿 数据
     * @throws Exception
     */
    public void getReimbursements() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        for(ShopInfo shop : list){
            List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));
            CreateReportSpecification body = new CreateReportSpecification();
            body.setReportType("GET_FBA_REIMBURSEMENTS_DATA");
            body.setMarketplaceIds(marketplaceIds);
            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.beginOfDay(DateUtil.yesterday())));
            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.endOfDay(DateUtil.yesterday())));

            // 第一步 创建报告
            ReportsApi reportsApi = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final String reportId = createReport(reportsApi, body);
            // 第二步 检验报告是否完成
            ReportsApi reportsApi2 = amazonUtil.getReportsApi(entityAuthority,shop,2.0);
            final Report report = getReport(reportsApi2, reportId);
            // 第三步 获取报告连接
            ReportsApi reportsApi3 = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final ReportDocument reportDocument = reportsApi3.getReportDocument(report.getReportDocumentId());
            // 第四步 下载报告
            String compressionAlgorithm = null;
            if(null != reportDocument.getCompressionAlgorithm()){
                compressionAlgorithm = reportDocument.getCompressionAlgorithm().getValue();
            }
            download(reportDocument.getUrl(),compressionAlgorithm,shop);

        }
    }

    @Override
    public void download(String url, String compressionAlgorithm, ShopInfo shop) throws IOException, IllegalArgumentException {
        OkHttpClient httpclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = httpclient.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println(
                    String.format("Call to download content was unsuccessful with response code: %d and message: %s",
                            response.code(), response.message()));
            return;
        }

        try (ResponseBody responseBody = response.body()) {
            MediaType mediaType = MediaType.parse(response.header("Content-Type"));
            Charset charset = mediaType.charset();
            if (charset == null) {
                throw new IllegalArgumentException(String.format(
                        "Could not parse character set from '%s'", mediaType.toString()));
            }

            Closeable closeThis = null;
            try {
                InputStream inputStream = responseBody.byteStream();
                closeThis = inputStream;

                if ("GZIP".equals(compressionAlgorithm)) {
                    inputStream = new GZIPInputStream(inputStream);
                    closeThis = inputStream;
                }

                // This example assumes that the download content has a charset in the content-type header, e.g.
                // text/plain; charset=UTF-8
                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                    closeThis = inputStreamReader;

                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    closeThis = reader;

                    int lineNumber = 0;
                    String line;
                    Map<String,Integer> titleList = new HashMap<String,Integer>();
                    List<TmpReimbursements> list = new ArrayList<>();
                    while ((line = reader.readLine()) != null) {
                        String[] info = line.split("\t");
                        int length = info.length;
                        if (lineNumber == 0) {
                            for (int i = 0; i < length; i++) {
                                titleList.put(info[i],i);
                            }
                        } else {
                            TmpReimbursements tmp = new TmpReimbursements();
                            tmp.setCreateTime(new Date());
                            String approval_date= GeneralUtil.getStrValue(info, titleList, "approval-date");
                            String reimbursement_id= GeneralUtil.getStrValue(info, titleList, "reimbursement-id");
                            String case_id= GeneralUtil.getStrValue(info, titleList, "case-id");
                            String amazon_order_id= GeneralUtil.getStrValue(info, titleList, "amazon-order-id");
                            String reason= GeneralUtil.getStrValue(info, titleList, "reason");
                            String sku= GeneralUtil.getStrValue(info, titleList, "sku");
                            String fnsku = GeneralUtil.getStrValue(info, titleList, "fnsku");
                            String asin= GeneralUtil.getStrValue(info, titleList, "asin");
                            String product_name = GeneralUtil.getStrValue(info, titleList, "product-name");
                            String condition= GeneralUtil.getStrValue(info, titleList, "condition");
                            String currency_unit= GeneralUtil.getStrValue(info, titleList, "currency-unit");
                            String amount_per_unit= GeneralUtil.getStrValue(info, titleList, "amount-per-unit");
                            String amount_total= GeneralUtil.getStrValue(info, titleList, "amount-total");
                            Integer quantity_reimbursed_cash= GeneralUtil.getIntegerValue(info, titleList, "quantity-reimbursed-cash");
                            Integer quantity_reimbursed_inventory= GeneralUtil.getIntegerValue(info, titleList, "quantity-reimbursed-inventory");
                            Integer quantity_reimbursed_total= GeneralUtil.getIntegerValue(info, titleList, "quantity-reimbursed-total");
                            String original_reimbursement_id= GeneralUtil.getStrValue(info, titleList, "original-reimbursement-id");
                            String original_reimbursement_type= GeneralUtil.getStrValue(info, titleList, "original-reimbursement-type");

                            tmp.setSid(shop.getId());
                            tmp.setCountry(shop.getMid());
                            tmp.setApprovalDate(AmzDateUtils.getDatePlus(approval_date));
                            tmp.setReimbursementId(reimbursement_id);
                            tmp.setCaseId(case_id);
                            tmp.setAmazonOrderId(amazon_order_id);
                            tmp.setReason(reason);
                            tmp.setMsku(sku);
                            tmp.setFnsku(fnsku);
                            tmp.setAsin(asin);
                            tmp.setItemName(product_name);
                            tmp.setCondition(condition);
                            tmp.setCurrencyUnit(currency_unit);
                            tmp.setAmountPerUnit(amount_per_unit);
                            tmp.setAmountTotal(amount_total);
                            tmp.setQuantityReimbursedCash(quantity_reimbursed_cash);
                            tmp.setQuantityReimbursedInventory(quantity_reimbursed_inventory);
                            tmp.setQuantityReimbursedTotal(quantity_reimbursed_total);
                            tmp.setOriginalReimbursementId(original_reimbursement_id);
                            tmp.setOriginalReimbursementType(original_reimbursement_type);

                            list.add(tmp);
                        }
                        lineNumber++;
                        // Process line by line.
                    }
                    tmpReimbursementsService.saveBatch(list);
                } else {
                    //Handle content with binary data/other media types here.
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("处理Listing数据异常",e);
            } finally {
                if (closeThis != null) {
                    closeThis.close();
                }
            }
        }
    }

}
